package com.example.gprcdemo.ui.home;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.gprcdemo.GRPCServer;
import com.example.gprcdemo.databinding.FragmentHomeBinding;
import com.example.gprcdemo.helloworld.GreeterGrpc;
import com.example.gprcdemo.helloworld.HelloReply;
import com.example.gprcdemo.helloworld.HelloRequest;
import com.example.gprcdemo.GRPCClient;

import java.io.IOException;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.netty.NettyServerBuilder;
import io.grpc.stub.StreamObserver;

public class HomeFragment extends Fragment {
    //https://blog.csdn.net/haohulala/article/details/129211997
    private static final String TAG = "GrpcDemo";
    private static final int PROT = 9004;
    //adb forward tcp:8004 tcp:56322
    private static final String NAME = "hello world的Name";
    private static final String HOST = "localhost";
    int requestCode = 100;
    private FragmentHomeBinding binding;
    private GRPCClient grpcClient;
    GRPCServer grpcServer;
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        HomeViewModel homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        final TextView textView = binding.textHome;
        homeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
        grpcClient=new GRPCClient(requireContext());
        grpcServer = new GRPCServer(requireContext());
        startServer(PROT);
        grpcServer.start();
        binding.btgrpc.setOnClickListener(v -> {
           // startClient(HOST, PROT, NAME);
            requestCode = 200;
           grpcClient.simpleHello();

        });
        binding.btgrpc2.setOnClickListener(v -> {
            grpcClient.clientStream();
        });
        binding.btgrpc3.setOnClickListener(v -> {
            grpcClient.serverStream();
            grpcClient.dowolandFile(fileName);
            fileName= "a2";
            grpcClient.dowolandFile(fileName);

        });
        binding.btgrpc4.setOnClickListener(v -> {
            grpcClient.bothFlowStream();
        });
        return root;
    }
    String fileName= "a3";

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    void sendInfo(String info) {
        Log.d(TAG, info);
    }

    private void startServer(int port) {
        try {
            NettyServerBuilder.forPort(port)
                    .addService(new GreeterImpl())
                    .build()
                    .start();
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, e.getMessage());
        }
    }

    private class GreeterImpl extends GreeterGrpc.GreeterImplBase {
        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
            responseObserver.onNext(sayHello(request));
            responseObserver.onCompleted();
        }

        private HelloReply sayHello(HelloRequest request) {
            int newcode = 200;
            String msg = "我是android服务器返回的 " + request.getName();
            if (request.getName() .equals("200")) {
                newcode = 400;
                msg = "fail  " + request.getName();
                ;
            }
            Log.d(TAG, msg);
            return HelloReply.newBuilder()
                    .setMessage(msg)
                    .build();
        }
    }

    //简单一元模式 客户端和服务端进行一问一答的通信
    private void startClient(String host, int port, String name) {
        ManagedChannel mChannel = ManagedChannelBuilder.forAddress(host, port)
                .usePlaintext()
                .build();
        GreeterGrpc.GreeterStub stub = GreeterGrpc.newStub(mChannel);

        HelloRequest request = HelloRequest.newBuilder().setName(name).build();
        stub.sayHello(request, new StreamObserver<HelloReply>() {
            @Override
            public void onNext(HelloReply value) {
                //Log.d(TAG, "sayHello onNext.");
                Log.d(TAG,  ":" + value.getMessage());
            }

            @Override
            public void onError(Throwable t) {
                Log.d(TAG, "sayHello onError.");
            }

            @Override
            public void onCompleted() {
                Log.d(TAG, "sayHello onCompleted.");
            }
        });
    }

}